import React, { useEffect, useState } from 'react'
import CarouselCard from './CarouselCard'

const Carousel1 = ({ children }) => {
  const count = React.Children.count(children)
  if (count <= 1 || !children.every((el) => el.type === CarouselCard)) {
    throw new Error(
      'Carousel1 的children必须为CarouselCard元素的数组，' + '而且长度不小于2'
    )
  }
  const { 0: first, [children.length - 1]: last } = children
  // [last, ...children, first]
  const newChildren = [
    React.cloneElement(last, { key: '$first' }),
    ...children,
    React.cloneElement(first, { key: '$last' }),
  ]
  const [current, setCurrent] = useState(1)
  const [disableTranstion, setDisableTranstion] = useState(false)

  useEffect(() => {
    if (disableTranstion) {
      setDisableTranstion(false)
    }
  }, [disableTranstion])

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrent(current => current+1)
    }, 2000)
    return () => clearInterval(timer)
  }, [])

  return (
    <div>
      <div className="carousel1">
        <ul
          className={`carousel1-list ${disableTranstion ? '' : 'transition'}`}
          style={{
            left: -(current * 100) + '%',
          }}
          onTransitionEnd={() => {
            if (current === count + 1) {
              // 向右到头
              setDisableTranstion(true)
              setCurrent(1) // 重置到开头
            } else if (current === 0) {
              // 向左到头
              setDisableTranstion(true)
              setCurrent(count) // 重置到结尾
            }
          }}
        >
          {newChildren}
        </ul>
        <ul className='indicator'>
          {
            [...Array(count)].map((_, index) => (
              <li key={index} className={`${
                index+1===current?'current': ''
              }`} onClick={
                () => setCurrent(index+1)
              }/>

            ))
          }
        </ul>
      </div>
      <button
        onClick={() => {
          let next = current - 1
          setCurrent(next <= 0 ? 0 : next)
        }}
      >
        👈
      </button>
      <button
        onClick={() => {
          let next = current + 1
          setCurrent(next >= count + 1 ?
            count + 1 : next)
        }}
      >
        👉
      </button>
    </div>
  )
}

export default Carousel1
